#include "screenshot.h"
#include <QMouseEvent>
#include <QtMath>
#include <QPainter>
#include <QClipboard>
#include <QDateTime>
#include <QApplication>

ScreenShot::ScreenShot(QPixmap pix, QWidget *parent):QLabel(parent),ifChoose(false)
{
    setPixmap(pix);
    showFullScreen();
}

void ScreenShot::mousePressEvent(QMouseEvent *ev){
    if(ev->button()==Qt::LeftButton){
        ifChoose=true;
        origin=cursor().pos();
    }
}

void ScreenShot::mouseMoveEvent(QMouseEvent *ev){
    if(ifChoose){
        QPoint p=cursor().pos();
        int top=p.y()<origin.y()?p.y():origin.y();
        int left=p.x()<origin.x()?p.x():origin.x();
        rect.setLeft(left);
        rect.setTop(top);
        rect.setHeight(qAbs(p.y()-origin.y()));
        rect.setWidth(qAbs(p.x()-origin.x()));
        update();
    }
}

void ScreenShot::mouseReleaseEvent(QMouseEvent *ev){
    QPixmap pix(rect.width(),rect.height());
    render(&pix,QPoint(),QRegion(rect));
    QClipboard *clipBoard=QApplication::clipboard();
    QString fileName=QDateTime::currentDateTime().toString("yyyyMMddhhmmss.png");
    pix.save(fileName);
    clipBoard->setImage(pix.toImage());
    close();
}

void ScreenShot::paintEvent(QPaintEvent *e){
    QLabel::paintEvent(e);
    if(ifChoose){
        QPainter p(this);
        p.setPen(QColor(Qt::red));
        p.drawRect(rect);
    }
}
